package com.bcxj.routeplan.utils;

import com.bcxj.internalcommon.util.RedisData;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.registerModule(new JavaTimeModule()); // 支持 LocalDateTime
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 忽略未知字段
    }

    public static <T> RedisData<T> parseRedisData(String json, Class<T> dataType) throws Exception {
        // 第一步：将整个 JSON 解析为 RedisData<String>
        RedisData<String> redisDataWithString = objectMapper.readValue(
            json, 
            new TypeReference<RedisData<String>>() {}
        );

        // 第二步：将 data 字符串解析为具体类型 T
        T data = objectMapper.readValue(redisDataWithString.getData(), dataType);

        return new RedisData<>(
            redisDataWithString.getExpireTime(),
            data
        );
    }
}